package smartgrid;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.orm.PersistentException;

public class EltricStats extends Stats {

    private SessionFactory s;

    /**
     * Retorna estatísticas monetárias.
     * @param contract Contrato a partir do qual serao calculados os custos.
     * @return 
     */
    public MoneyStats getMoneyStats() {
        try {
            Tariff tariff = null;
            MoneyStats mstats = new MoneyStats();
            Price price = null;

            float totalMoney = 0;
            int dataLineHour = 0;
            int dataLineMin = 0;

            GregorianCalendar timeStamp = new GregorianCalendar();




            for (DataLine dataline : this.getDataLine_role()) {
                price = null;
                tariff = dataline.getTariff();

                dataLineMin = dataline.getMinuto();
                dataLineHour = dataline.getHora();


                smartgrid.PriceCriteria priceCrit = new PriceCriteria();
                priceCrit.add(Restrictions.eq("Tariff_Prices_role.id", tariff.getID()));

                priceCrit.add(Restrictions.sqlRestriction("((StartHour = " + dataLineHour + " and StartMinute <= " + dataLineMin + ")"
                        + " or StartHour < " + dataLineHour + ") and "
                        + "((EndHour = " + dataLineHour + " and EndMinute >= " + dataLineMin + ")"
                        + " or EndHour > " + dataLineHour + ")"));

                price = smartgrid.Price.loadPriceByCriteria(priceCrit);

                if (price != null) {
                    totalMoney += (dataline.getValue() * price.getEuros());
                }
            }


            mstats.setTotal(totalMoney);

            return mstats;

        } catch (PersistentException ex) {
            Logger.getLogger(ContractsManager.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;

    }

    /**
     * Retorna estatísticas monetárias.
     * @param tariff Tarifário a partir do qual será calculado o custo.
     * @return 
     */
    public MoneyStats getMoneyStats(Tariff tariff) {
        try {

            MoneyStats mstats = new MoneyStats();
            Price price = null;
            float totalMoney = 0;
            int dataLineHour = 0;
            int dataLineMin = 0;

            GregorianCalendar timeStamp = new GregorianCalendar();

            for (DataLine dataline : this.getDataLine_role()) {
                price = null;

                dataLineMin = timeStamp.get(Calendar.MINUTE);
                dataLineHour = timeStamp.get(Calendar.HOUR_OF_DAY);

                smartgrid.PriceCriteria priceCrit = new PriceCriteria();
                priceCrit.add(Restrictions.eq("Tariff_Prices_role.id", tariff.getID()));

                priceCrit.add(Restrictions.sqlRestriction("((StartHour = " + dataLineHour + " and StartMinute <= " + dataLineMin + ")"
                        + " or StartHour < " + dataLineHour + ") and "
                        + "((EndHour = " + dataLineHour + " and EndMinute >= " + dataLineMin + ")"
                        + " or EndHour > " + dataLineHour + ")"));

                price = smartgrid.Price.loadPriceByCriteria(priceCrit);


                if (price != null) {
                    totalMoney += (dataline.getValue() * price.getEuros());
                }

            }


            mstats.setTotal(totalMoney);

            //igual ao electric stats?????????
            mstats.setDataLine_role(this.getDataLine_role());
            mstats.setEndTime(this.getEndTime());
            mstats.setStartTime(this.getStartTime());
            mstats.setInterval(this.getInterval());

            return mstats;
        } catch (PersistentException ex) {
            Logger.getLogger(EltricStats.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    @Override
    public String getJson() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public static void main(String[] args) throws PersistentException {
        double media_tarifario = 0;
        List<Price> precos = new ArrayList<Price>();
        Price p1 = new Price();
        Price p2 = new Price();
        Price p3 = new Price();
       
        double minuteStart = 0;
        double minuteEnd = 0;
        
        p1.setStartHour(0);
        p1.setStartMinute(0);
        p1.setEndHour(8);
        p1.setEndMinute(0);
        p1.setEuros(10);
        
        p2.setStartHour(8);
        p2.setStartMinute(0);
        p2.setEndHour(24);
        p2.setEndMinute(0);
        p2.setEuros(100);
        
        p3.setStartHour(16);
        p3.setStartMinute(0);
        p3.setEndHour(24);
        p3.setEndMinute(0);
        p3.setEuros(10);
        precos.add(p1);
        precos.add(p2);
       // precos.add(p3);
        for (Price p : precos) {
            minuteStart = p.getStartMinute() == 0 ? 0 : p.getStartMinute()/60;
            minuteEnd = p.getEndMinute() == 0 ? 0 : p.getEndMinute()/60;
            
            media_tarifario += ((((p.getEndHour() + minuteEnd) -
                    (p.getStartHour() + minuteStart)))/24) * p.getEuros();
        }
        System.out.println("Média do tarifário " + media_tarifario);

    }
}